import NodeRSA from 'node-rsa'
import crypto from 'crypto'
import moment from 'moment'
import env from '@/config/env'
import {apiGetSign} from '@/service/apiService'

let arrSignParams = new Array(
  "appAuthToken",       // 商户授权令牌
  "appId",              // 通联分配给开发者的应用ID
  "bizContent",         // 请求业务参数集合
  "charset",            // 请求报文字符集:默认utf8
  "format",             // 报文格式:默认JSON
  "signType",           // 商户生成签名字符串所使用的签名算法类型:默认RSA
  "timestamp",          // 时间戳
  "version");           // 版本号

export const custsign = (key, data) => {
  console.log("custsign");

  // 私钥签名
  let prikeyStr = '-----BEGIN PRIVATE KEY-----\n' +
                  'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6gBVE4KZbRgbr/B7vjmiSD8vuBRbOKBBIShGOyV9vrfCzgfCJ0rqDglbUp1VLqDavR5y4BxW8Ysd4ztu5hG+wj3BPFDtZcRbKvLzHsxKkbUxM0VtxRtu618HXsF8zNQ9gbWLBTwsEKTc+rFbBMVVAxBsHQ3GVMY0VaazAHyJuzvJTJ+cWzT5xQdFuJjWfZKzQV6pJxwIGBH4G1EJXEqYucxK5qPyeAuNrh7xJFJRbT+OAS8TxoLNbCbeHMAlZrC+Vl2zNb8AjrjbiFufL27CcsL9VU4PZ25CDC4uUDopIfoaRPCvesFrDibWgSTpy5NAeDRwU118+Yc939oNaQgPFAgMBAAECggEAAMQSdtw8Lhc1Pu0j2j23eoIU9OORmrFr/7JJmnUV00Aowy9jthHCVcI2IRO6RoSxwoMXD/XXfQKRspJ0ntXZiwCnOpB7Rw7BjTS8pk5x9bnECnOT8I8nFG3tQwKks7rZMnXlHMmMmXYPlbwFKp3x0fiOfQCTnkQXixeKSzjVgsuM93lRXXftVkQFVvMyBQDLQGd9ZwnRejFoSSNiaAicLkMguNGv7RCaSXZ/nkzAglHVNu59E2FBj5tpAbjZnlEKeAIWRdVzXm1K7Dk08E0+u1caCGTXH25r7Fl5vK+uk/GzdHFtSE0KVF9hNChTclSO0UxM2G6jLmsZBdJM5sdpsQKBgQD4KJUGI2n45nfQYEToJhzEPT6bNlKdn+dsqoSn1FW//ALWgP3JOqJbkqcJQrR9UH6cLK5g0Rh8BNOoS0nRyE6d7WX0YZ9JYZqsDMXNh/w41o09nXRJDP14QGrCCVMgrEYz5v+3xKlEDBJnC4dJCG3GTSBwpdxordfU+N4iQWG8VwKBgQDAZLtjdsdUTkDeKRdGwz3h/+mvL18/bbJafTx4R1eZi7DLOAH/2nMVX3fbksvA9hwvOln8tfUc+FhC4P7Camt/RDMbAqI1G6wTckWrlPR/XsF0EP6rmE6suWqfzvQYb+3jYJCwa4Vm5sHmqiFvtGFK54Ev5oEJq7i1rnttqJxvQwKBgQDEmtJGRLRmn6D5E+xDyD4uMx9wtL8LZm5hJ09l79HoAm71JsjqLmwHBM8VhSWdyrIkZTnaNo6hYumVgeCANaQjdru5u8YIyy1RdeUYis4G8eSAlkhUv9fo95AdHmofjp0n7bFXFJXN9Yp23SlXcTgXTW+QD7fpryE599l1ZjtajQKBgQCDQLVuZ8wYwcITTekpR21iTxp3f1P1i7rPbPzh+ZnTkK8uFKmYiMlWXWkBjSYgIEaeGarmcqQj/XEJP0HOFJf9nONYm/VZUeWU5rKNGfOrKVPFAQscua2CvIP3PlLckQ+zvV84XEIIL4k8+fgRovd1CHbj3NdPZ619lOlzqEIAzQKBgA9l7KVmDrTobIPojPsf0/W3x8cof4dmSn4dTep5DTP+BjCtob5SGldy/11NcvyOuvRu1AwrBmqAo+QTm0SUBCkIta6p4KxWcEP1cX31v6ImbbtuK6qclLfceQmXMnULvoWt2PZosjjK4aPCifnfMjeRyBXCHEDWVMefZjgWL/6j\n' +
                  '-----END PRIVATE KEY-----';
  let prikey = new NodeRSA(prikeyStr);
  // prikey.setOptions({encryptionScheme: 'pkcs8', signingScheme: 'pkcs1-sha1'});
  prikey.setOptions({encryptionScheme: 'pkcs1', signingScheme: 'pkcs1-sha1'});
  console.log(prikey);
  console.log('isPrivate:', prikey.isPrivate());
  // let buf = new Buffer('123456');
  let buf = '123456';
  console.log("data:", buf);
  let sign = prikey.sign(buf);
  console.log("custsign:", sign.toString('base64'));

  // 公钥验签
//   let pubkeyStr = '-----BEGIN PUBLIC KEY-----\n' +
// 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuoAVROCmW0YG6/we745okg/L7gUWzigQSEoRjslfb63ws4HwidK6g4JW1KdVS6g2r0ecuAcVvGLHeM7buYRvsI9wTxQ7WXEWyry8x7MSpG1MTNFbcUbbutfB17BfMzUPYG1iwU8LBCk3PqxWwTFVQMQbB0NxlTGNFWmswB8ibs7yUyfnFs0+cUHRbiY1n2Ss0FeqSccCBgR+BtRCVxKmLnMSuaj8ngLja4e8SRSUW0/jgEvE8aCzWwm3hzAJWawvlZdszW/AI6424hbny9uwnLC/VVOD2duQgwuLlA6KSH6GkTwr3rBaw4m1oEk6cuTQHg0cFNdfPmHPd/aDWkIDxQIDAQAB\n' +
// '-----END PUBLIC KEY-----';
//   let pubkey = new NodeRSA(pubkey);
//   console.log(pubkey);
//   console.log('isPublic:', pubkey.isPublic());
//   // pubkey.setOptions({encryptionScheme: 'pkcs1', signingScheme: 'pkcs1-sha1'});
//   let ret = false;
//   ret = pubkey.verify(buf, sign);
//   console.log("pubkey.verify:", ret);

  return "custsign"
}

export const custsign2 = (key, data) => {
  console.log("custsign2 begin");
  let prikeyStr = '-----BEGIN PRIVATE KEY-----\n' +
                  'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6gBVE4KZbRgbr/B7vjmiSD8vuBRbOKBBIShGOyV9vrfCzgfCJ0rqDglbUp1VLqDavR5y4BxW8Ysd4ztu5hG+wj3BPFDtZcRbKvLzHsxKkbUxM0VtxRtu618HXsF8zNQ9gbWLBTwsEKTc+rFbBMVVAxBsHQ3GVMY0VaazAHyJuzvJTJ+cWzT5xQdFuJjWfZKzQV6pJxwIGBH4G1EJXEqYucxK5qPyeAuNrh7xJFJRbT+OAS8TxoLNb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m/VZUeWU5rKNGfOrKVPFAQscua2CvIP3PlLckQ+zvV84XEIIL4k8+fgRovd1CHbj3NdPZ619lOlzqEIAzQKBgA9l7KVmDrTobIPojPsf0/W3x8cof4dmSn4dTep5DTP+BjCtob5SGldy/11NcvyOuvRu1AwrBmqAo+QTm0SUBCkIta6p4KxWcEP1cX31v6ImbbtuK6qclLfceQmXMnULvoWt2PZosjjK4aPCifnfMjeRyBXCHEDWVMefZjgWL/6j\n' +
                  '-----END PRIVATE KEY-----';
  const hashes = crypto.getHashes();
  console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
  const sign = crypto.createSign('RSA-SHA1');
  sign.update('123456');
  let ret = sign.sign({key:prikeyStr, padding:crypto.constants.RSA_PKCS1_PADDING}, 'base64');
  console.warn('custsign2:', ret);

  // 公钥验签
  let pubkeyStr = '-----BEGIN PUBLIC KEY-----\n' +
                  'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuoAVROCmW0YG6/we745okg/L7gUWzigQSEoRjslfb63ws4HwidK6g4JW1KdVS6g2r0ecuAcVvGLHeM7buYRvsI9wTxQ7WXEWyry8x7MSpG1MTNFbcUbbutfB17BfMzUPYG1iwU8LBCk3PqxWwTFVQMQbB0NxlTGNFWmswB8ibs7yUyfnFs0+cUHRbiY1n2Ss0FeqSccCBgR+BtRCVxKmLnMSuaj8ngLja4e8SRSUW0/jgEvE8aCzWwm3hzAJWawvlZdszW/AI6424hbny9uwnLC/VVOD2duQgwuLlA6KSH6GkTwr3rBaw4m1oEk6cuTQHg0cFNdfPmHPd/aDWkIDxQIDAQAB\n' +
                  '-----END PUBLIC KEY-----';
  const verify = crypto.createVerify('RSA-SHA1');
  verify.update('123456');
  let ret2 = false;
  ret2 = verify.verify({key:prikeyStr, padding:crypto.constants.RSA_PKCS1_PADDING}, ret, 'base64');
  console.log("custsign2 end:", ret2);
}

/**
 * [使用RSA-SHA1方式创建签名]
 * @param  {[<string>utf8]} data [待签名数据]
 * @return {[<strng>]base64}     [签名值]
 */
export const createSign = (data) => {
  let prikeyStr =
"-----BEGIN RSA PRIVATE KEY-----\n" +
"MIIEpQIBAAKCAQEA4EdAAeKNowN7GPTWynE2ltfN5pNoB+L6VXGDbDpYoEes/04P\n" +
"3iq8Gn/MPrNpGZO+KDn/XyK102dmiJ+xH/ea6MeQ6X3LwvxmTMV1x+up5UCI8IJZ\n" +
"CERCn1eXvmGK4HyBZO9sdlWNbaYmBMywtP3jVdLV+em6DYI3FEok5gon7a19axdT\n" +
"OU9iTsz/CZHtmRdWmhRvnYr0AcsNvklOKqAeBz1NmU3ZDC9ZAOQ1jl+XfxrzIQbF\n" +
"JFbzkt/sS/UV1hZsdDCEeqxSQaFslBcsOb1nfDLl2BOZVkA031f/nrXJZE4IYdmb\n" +
"wq243KQMjdh8qyrFtOxWoYAWlyMXAHur7xPXIQIDAQABAoIBAQDYZabqqq/Cs98Y\n" +
"K1T7q9TiIoM2kM/1nBmyS35k9L8Cl2XiSG2jDVTFtL1bWjx0Q0tdAOjX4GPUAJa8\n" +
"CGkc0QmUxMmboJb0IhiKxpNoPIiG/IekmABTq5kkqZ1uQit/gmJPA3yBiPaW75ML\n" +
"Wny9haLN8kongk7ULen7F7cWhoIUHlyqW/C3ckdklVupWd97bkuTuO3H4kfgBhij\n" +
"ZahR0WAlpMwLrmDaeU/NMWqfbrRSRlL0sZBdTnFvNf6UiKEZwKMviGikVW3n62kD\n" +
"XPoj0aSowqhzsY0TRBzVh8EVEf4HCzgK5uWVrUJQSCjBhMeonZIpW78brh5LmN5M\n" +
"twdQ1DoBAoGBAPZ4/uce8/gf19IhFJyD1aHpblsHIvL08Jv/fLQFcFh9KaDmPQyY\n" +
"jNcVS3UEAvkEvzugow0vzA7EsIseBEZLWJKvQ6u2afKUvoirjD1pSB2JZj11nIBU\n" +
"BLVk5bJVyxgxSvF75DvbsCjnka3eF6pjkFWJDh2UaKMvsELsvF9w8WsxAoGBAOjy\n" +
"oJmPvfeLPDNVkJu5IYQ63no3di7J1dWhfszRXl6XU+JlcFcLBaUbgEzZMByAnVRF\n" +
"D7V3ScaCF7aTTx//2Shhpo6H+jzFroo7YdnlkVOXGLs9rEAz2oNE5CJFTRsN15rJ\n" +
"0WPVx/gLgaImuygqg6JWB28qRJVEOvnytNycNU7xAoGBAOlDwDNq9wko0fBcQI6U\n" +
"svZG35ulGG2KZcGuPg5+a0JESsatwK+QHRNeYwi/IDUfSgGb2VUcnGqJunAfm3oP\n" +
"yycgWtJDlOfx4JWmjdZ9MrRJmoqmKdTGL6KheEacrdcap8v+LhZ8p68+4oAEBq/L\n" +
"BQn+6W4TTCjNdGsSdIF7efCxAoGBALs+o/crgrBjPA2rXqS9qAJI66HjyNyNIpQo\n" +
"zurF9IwmKahWj3l4A56Wv4eGINUYUN528MyVyTiGQ5dfS3/WQPDjpWT2Sh/laon0\n" +
"d5AVpr5BOwDu7vFgfOl9S798YyE2/DKQvP35zlZEsXvslA4SNmMbsbgaiqxM/vcA\n" +
"r36RFYyRAoGACPnKCBWu4rV1RXZyNLFvng4bN8AP0tGFMmmIQWd6Rnd+iGi6kQS1\n" +
"R0MHpy+8DN1kRDXyNFT/KSc+rPjBgqW5+3TkzTQKD5BVIQmtgidDFHHltVcbVvtb\n" +
"0VnxEQIANuh63fTVBcE+/hb7T07ZGsAoli+CUF15G7+yayCQCNvhSwQ=\n" +
"-----END RSA PRIVATE KEY-----";

  const sign = crypto.createSign('RSA-SHA1');
  sign.update(data);
  let ret = sign.sign({key:prikeyStr, padding:crypto.constants.RSA_PKCS1_PADDING}, 'base64');
  console.warn('myCreateSign:', ret);
  return ret;
}

/**
 * [产生带签名数据]
 * @param  {[strng]} param [待签名参数]
 * @return {[string]}      [待签名数据]
 */
export const createSignData = (param) => {
  if (!param.appId) {
    param.appId = env.appId;
    // console.log("appId not exist, set default [%s]", param.appId);
  }
  if (!param.charset) {
    param.charset = "utf-8";
    // console.log("charset not exist, set default [%s]", param.charset);
  }
  if (!param.signType) {
    param.signType = "RSA";
    // console.log("signType not exist, set default [%s]", param.signType);
  }
  if (!param.timestamp) {
    param.timestamp = moment().format('YYYYMMDDHHmmss');
    // console.log("timestamp not exist, set default [%s]", param.timestamp);
  }
  if (!param.version) {
    param.version = "1.0";
    // console.log("version not exist, set default [%s]", param.version);
  }
  if (!param.bizContent) {
    param.bizContent = {};
    // console.log("version not exist, set default {}");
  }

  let signData = "";
  let arrLen = arrSignParams.length;
  for (let i = 0; i < arrLen; i++) {
    if (arrSignParams[i] in param) {
      let tmp = arrSignParams[i] + "=";
      if (typeof(param[arrSignParams[i]]) === "object") {
        // 对象需要转换成字符串后拼接
        // console.log(arrSignParams[i], typeof(param[arrSignParams[i]]));
        // console.log("JSON.stringify:", JSON.stringify(param[arrSignParams[i]]));
        tmp += JSON.stringify(param[arrSignParams[i]]);
      }
      else {
        tmp += param[arrSignParams[i]];
      }
      
      // console.log(tmp);
      if (signData.length > 0) {
        signData += "&";
      }
      signData += tmp;
    }
  }
  return signData;
}


export const rsaEncStr = (str) => {
        let pubkey = '-----BEGIN CERTIFICATE-----\n' +
'MIIDhzCCAm+gAwIBAgIGASYIUVcqMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDElMCMGA1UECwwcQWxsaW5wYXkgUHJpbWFyeSBDZXJ0aWZpY2F0ZTAeFw0xMDAxMDcxMDI1MzNaFw0zMDAxMDIxMDI1MzNaMGQxCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDEqMCgGA1UECwwhQWxsaW5wYXkgRGlnaXRhbCBTaWduIENlcnRpZmljYXRlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDG7b3C1oiXQrB7AZL8Vjk0A2ifrAMUh6JTODyDueaFVZjCtJAjLtFLQQUM7n+ZTVRRiBeJ9uwcK2RPbp9SDraBcuNEi/e36cqTH6MiCsdzhBzdF2gthB2UdswNMgs9qoudxj1NFwq7LlzU24iDz//vTq2GBf8Iiy5ByBtKsZaA4QIDAQABo4HHMIHEMB0GA1UdDgQWBBRe7l/HEp+14Dq+psIg0hQgg/nPdDCBjgYDVR0jBIGGMIGDgBSBWR3Bvx8To7TrecKhCM4smeabN6FjpGEwXzELMAkGA1UEBhMCQ04xKTAnBgNVBAoMIEFsbGlucGF5IE5ldHdvcmsgU2VydmljZXMgQ28uTHRkMSUwIwYDVQQLDBxBbGxpbnBheSBQcmltYXJ5IENlcnRpZmljYXRlggYBJghKHowwEgYDVR0TAQH/BAgwBgEB/wIBADANBgkqhkiG9w0BAQUFAAOCAQEAeCaF1E08oVl+tBHAhHxr8sLjOmFcQ9q1syx4CEMhFMqF4hgrCiGwY2qxJiDFWaY28BMEJAXUt5j20B5SNy6qeEaPFD1h95iESMLM8PFf/hSDePT8V8R4sedzO9sHNv1vYARPTHlFbqYqGN/kCTuC1HeyL+KpwTrZ3Q1uUWGitzZpe8BlwlxV0hsuB6qz48Ho3ge/s2RdkTS9Ewuxmya2tch6ZamvbY0XGEc2QBlu+b0kJ0xMott2ChPq2x0tHaP7aVHTrjSRovqSXpG6VQycycJ9U8JTgd4z2pJQvySH9xLy80i42216J5svzbeJbSpkk5ccjbegx3mrQeDqrN9/kA==\n' +
'-----END CERTIFICATE-----\n';

  let buf = new Buffer(str);
  // console.log("str:", str);
  let encrypted = crypto.publicEncrypt(
    {key:pubkey, padding:crypto.constants.RSA_PKCS1_PADDING}, buf).toString('base64');

  return encrypted;
}

export const creatSignWrap = async (params) => {
  let ret = {isRetSuss: false, data: null, errmsg: ""};
  let signData = createSignData(params);
  let retData = await apiGetSign(signData);
  if (retData.errno != 0) {
    ret.errmsg = "生成签名失败";
    return ret;
  }
  ret.isRetSuss = true;
  ret.data = retData.sign;
  // console.log("ret.data:", ret.data)
  return ret;
}

